package com.situ.onlinebookstore.back.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.onlinebookstore.back.service.UserService;
import com.situ.onlinebookstore.common.entity.Admin;
import com.situ.onlinebookstore.common.entity.User;
import com.situ.onlinebookstore.common.mapper.UserMapper;
import com.situ.onlinebookstore.common.util.MD5Util;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    @Override
    public int add(User user) throws Exception {
        //1-验证重复
        User sUser = userMapper.selectByUsername(user.getUsername());
        if (sUser != null){
            throw new Exception("用户名已被使用");
        }
        //电话 邮箱

        //2-密码加密
        String salt = UUID.randomUUID().toString().substring(0,8);
        user.setPassword(MD5Util.getDBMD5(user.getPassword(),salt));
        user.setSalt(salt);
        user.setCreateTime(LocalDateTime.now());
        //3-保存到数据库
        return userMapper.insert(user);
    }


    @Override
    public int edit(User user) throws Exception {
        User sUser = userMapper.selectById(user.getId());
        if (sUser == null){
            throw new Exception("用户不存在");
        }
        //有可能只修改状态，也有可能只修改密码，也有可能修改电话邮箱姓名
        if (user.getPassword() != null) {//123
            //需要对密码进行双重MD5盐加密
            String salt = UUID.randomUUID().toString().substring(0, 8);
            user.setPassword(MD5Util.getDBMD5(user.getPassword(), salt));
            user.setSalt(salt);
        }
        //只修改状态
        if (user.getStatus() != null) {
            if (sUser.getStatus().equals(user.getStatus())) {
                throw new Exception("管理员状态不能重复修改！");
            }
        }
        //电话和邮箱是否允许重复
        return userMapper.update(user);
    }

    @Override
    public List search(User user) {
        return userMapper.select(user);
    }

    @Override
    public PageInfo searchForPage(Integer page, Integer limit, User user) {
        PageHelper.startPage(page, limit);
        List list = userMapper.select(user);
        return new PageInfo(list);
    }
}
